import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Intro from "@/app/intro/page";
import EntryRouteResolver from "@/components/Componentes/entry-route-resolver";
import {
  getAuthenticatedCachedEntryPath,
  isAuthenticatedToken,
  MARRIAGE_ENTRY_PATH_COOKIE,
} from "@/lib/entry-route-cache";
import {
  getSubmitPath,
  hasCompletedMarriageProfileBasics,
} from "@/lib/get-submit-path";
import { fetchProfileSSR } from "@/lib/ssr-fetch";
import { localizePath } from "@/translations/config";

export const dynamic = "force-dynamic";

export default async function LocaleEntryPage({
  params,
}: {
  params: Promise<{ lang: string }>;
}) {
  const [{ lang }, cookieStore] = await Promise.all([params, cookies()]);
  const token =
    cookieStore.get("HABIB_TOKEN")?.value ??
    cookieStore.get("habib_token")?.value;
  const hasToken = isAuthenticatedToken(token);

  // 1. If not authenticated, render <Intro /> instantly in SSR
  if (!hasToken) {
    return <Intro />;
  }

  // 2. Check cached entry path first
  const cachedEntryPath = getAuthenticatedCachedEntryPath(
    token,
    cookieStore.get(MARRIAGE_ENTRY_PATH_COOKIE)?.value,
  );

  if (cachedEntryPath) {
    if (cachedEntryPath === "/intro") {
      return <Intro />;
    }
    redirect(localizePath(cachedEntryPath, lang));
  }

  // 3. Deep SSR Profile Resolution: resolve profile & redirect directly on server
  const profile = await fetchProfileSSR(token);
  if (profile) {
    const isBasicsCompleted = hasCompletedMarriageProfileBasics(profile);
    if (!isBasicsCompleted) {
      return <Intro />;
    }

    const targetPath = getSubmitPath(profile);
    if (targetPath === "/intro") {
      return <Intro />;
    }

    redirect(localizePath(targetPath, lang));
  }

  // 4. Graceful Fallback if server fetch was unreachable
  return (
    <>
      <EntryRouteResolver anonymousEntryVisible={false} />
    </>
  );
}
